<?php

use tt\common\help\TableHelper;
use wechat\models\WeUser;
use wechat\models\WeUserOpenid;
use wechat\services\WeConfigService;

class m201809_181113_wechat extends \yii\db\Migration
{
    /**
     * {@inheritdoc}
     */
    public function safeUp()
    {
        (new WeUserOpenid())->createTable($this);

        // 将 we_user 中的 weixin_openid 迁移到 weUserOpenid 中
        if (TableHelper::columnExists(WeUser::tableName(), 'weixin_openid')) {
            // 表示已经迁移过数据了，不再迁移
            if (TableHelper::columnExists(WeUserOpenid::tableName(), 'user_openid')) {
                return;
            }
            $batchData = [];
            foreach (WeUser::find()->select(['id', 'weixin_openid'])->asArray()->each() as $record) {
                $batchData[] = [
                    'we_id' => $record['id'],
                    'openid' => $record['weixin_openid'],
                    'type' => WeConfigService::typeFromAppid($record['weixin_openid']),
                ];
            }

            WeUserOpenid::batchSave($batchData, ['we_id', 'openid', 'type']);
            // 移除
            TableHelper::dropColumn(WeUser::tableName(), ['weixin_openid', 'wechat_id']);
        }

        if (!TableHelper::columnExists(WeUserOpenid::tableName(), 'user_openid')) {
            $this->addColumn(WeUserOpenid::tableName(), 'user_openid', 'varchar(100) not null');
            $this->createIndex('user_openid', WeUserOpenid::tableName(), 'user_openid');
        }
    }
}
